package com.csy.tcshop.thirdservice.component;


import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.aliyuncs.http.MethodType;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

@Data
@Component
public class SmsComponent {

    @Value("${spring.cloud.alicloud.templateCode}")
    private String templateCode;//模板code
    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;
    @Value("${spring.cloud.alicloud.secret-key}")
    private String accessKey;

    public boolean sendSmsCode(String phone, String code) {
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        if (StringUtils.isEmpty(phone)) {
            return false;
        }
        DefaultProfile profile =
                DefaultProfile.getProfile("default", accessId, accessKey);
        IAcsClient client = new DefaultAcsClient(profile);
//        设置固定参数
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

//        设置发送相关参数
        request.putQueryParameter("PhoneNumbers", phone);//手机号
        request.putQueryParameter("SignName", "我的在线教育平台");//阿里云申请签名名称
        request.putQueryParameter("TemplateCode", templateCode);//阿里云申请的模板code
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));//JSONObject.toJSONString()可以将map集合变成json数据
//        最终发送
        try {
            CommonResponse commonResponse = client.getCommonResponse(request);
            boolean success = commonResponse.getHttpResponse().isSuccess();
            return success;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
